package cn.tedu.seckill.controller;

import cn.tedu.seckill.RabbitCompUtils;
import cn.tedu.seckill.service.SeckillService;
import com.jt.common.pojo.Seckill;
import com.jt.common.pojo.Success;
import com.jt.common.vo.SysResult;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/seckill/manage")
public class SeckillController {
    @Autowired
    private SeckillService seckillService;
    //秒杀商品seckill表格的数据查询 list
    @RequestMapping("/list")
    public List<Seckill> list(){
        return seckillService.list();
    }
    //查询单个秒杀商品
    @RequestMapping("/detail")
    public Seckill detail(Long seckillId){
        return seckillService.detail(seckillId);
    }
    //发起秒杀的核心逻辑
    /*
        接受请求,解析参数,生成消息,发送到rabbitmq
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping("/{seckillId}")
    public SysResult startSeckill(@PathVariable Long seckillId){
        //模拟一个手机号生成
        String userPhone="1889999"+new Random().nextInt(9999);
        //封装精简准确的消息
        String msg=userPhone+"/"+seckillId;
        //判断redis中是否有该用户的key值,有,说明秒杀过
        String key="seckill_user_"+userPhone;
        if(redisTemplate.hasKey(key)){
            //已经秒杀过了
            return SysResult.build(
                    202,
                    "已经秒杀过了,你还占便宜没够",
                    null);
        }
        //没有秒杀过,已经秒杀了,将数据写入
        redisTemplate.opsForValue().set(key,"");
        try{
            rabbitTemplate.convertAndSend(RabbitCompUtils.EX,
                    RabbitCompUtils.RK,msg);

            return SysResult.ok();
        }catch (Exception e){
            //发送消息失败
            e.printStackTrace();
            return SysResult.build(201,"秒杀失败",null);
        }
    }
    //展示成功者信息
    @RequestMapping("/{seckillId}/userPhone")
    public List<Success> getSuccess(@PathVariable Long seckillId){
        return seckillService.getSuccess(seckillId);
    }
}
